package com.weipu.common.facade.impl;

import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.CouponServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.model.CouponActiveModel;
import com.weipu.common.facade.model.CouponModel;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.Parmars;
import com.weipu.common.facade.model.PreviewOrderModel;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TonyYang 与Coupon相关的服务接口实现类
 */
public class CouponServiceProviderImpl extends BaseServiceProviderImpl
        implements CouponServiceProvider {

    // private static Map<String, String> mapUrl;

    private long oldTime;

    private long nowTime;

    // //方法名与URL的绑定
    // static{
    // mapUrl = new HashMap<String, String>();
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_FINDVALIDCOUPONSCOUNT,
    // Constant.FINDVALIDCOUPONSCOUNT_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_FINDCUSTOMERCOUPONS,
    // Constant.FINDCUSTOMERCOUPONS_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_FINDMARKETCOUPONS,
    // Constant.FINDMARKETCOUPONS_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_BINDCOUPON,
    // Constant.BINDCOUPON_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_PREVIEWORDER,
    // Constant.PREVIEWORDER_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_DELETE_COUPON,
    // Constant.DELETE_COUPON_URL);
    // mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_FIND_DISCOUNT_PRODUCTS,
    // Constant.FIND_DISCOUNT_PRODUCTS_URL);
    // }

    // /**
    // *
    // * 调用服务端接口put和post的封装方法
    // * @param methodName
    // * @param map
    // * @return 调用的接口的方法名，map存放的参数
    // * @return String [返回类型说明]
    // * @exception throws [违例类型] [违例说明]
    // * @see [类、类#方法、类#成员]
    // */
    // JSONObject postOrPutWebInterface(String Url, Object object,String
    // currencyCode)
    // throws DxException
    // {
    // String result = null;
    // JSONObject json = null;
    // try
    // {
    // oldTime = System.currentTimeMillis();
    // if(currencyCode==null){
    // currencyCode =
    // StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,"USD");
    // }
    // OkHttpHelper okHttpHelper=OkHttpHelper.getOkHttpHelperInstance();
    // result=okHttpHelper.syncPostRequest(Url, object, currencyCode);
    // nowTime = System.currentTimeMillis();
    // Logger.i("createOrderAndSetMobile", result);
    // json = returnResult(result);
    // }
    // catch (IOException e)
    // {
    // Logger.e(e.getMessage(), e);
    // //链接超时
    // if (e.getCause() instanceof SocketTimeoutException||e.getCause()
    // instanceof ConnectTimeoutException)
    // {
    // throw new
    // DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT);
    // }
    // else if(e.getCause() instanceof UnknownHostException){
    // throw new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
    // }
    // else
    // {
    // if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){
    // throw new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
    // }else{
    // throw new DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
    // }
    // }
    // }
    // return json;
    // }

    /**
     * 描述：查询对应Customer可用的Coupon数量
     *
     * @param CustomerID 顾客标识ID
     * @param SiteID     站点ID 取 1
     * @param SiteClient 客户端类型（PC、MobileApp、MobileWed、Pad）
     * @return 查询的数量值
     */
    @Override
    public int FindValidCouponsCount(long CustomerID, int SiteID,
                                     int SiteClient, String token) throws DxException {
        Parmars parmars = new Parmars();
        parmars.setCustomerID(CustomerID);
        parmars.setSiteID(SiteID);
        parmars.setSiteClient(SiteClient);
        parmars.setToken(token);
        // JSONObject jsonObject =
        // postOrPutWebInterface(Constant.FINDVALIDCOUPONSCOUNT_URL,
        // parmars,null);
        // if(jsonObject!=null){
        // JSONObject data = jsonObject.optJSONObject(Constant.JSON_DATA);
        // if(data!=null){
        // return data.optInt("Count");
        // }
        // }
        JSONObject data = requestHttpPostData(Constant.FINDVALIDCOUPONSCOUNT_URL,
                parmars);
        if (data != null) {
            return data.optInt("Count");
        }
        return 0;
    }

    /**
     * 描述：查询Customer下的所有手动Coupon
     *
     * @param CustomerID 顾客标识ID
     * @param SiteID     站点ID
     * @param SiteClient 客户端类型（PC、MobileApp、MobileWed、Pad）
     * @param Status     活动状态数组，为空则返回所有状态下的Coupon，值为（NotUsed,Used,Expired）
     * @param PageIndex  页码，从0开始
     * @param PageSize   每页显示的条数
     * @return 查询到的Coupon集合
     */
    @Override
    public ArrayList<CouponModel> FindCustomerCoupons(long CustomerID,
                                                      int SiteID, int SiteClient, String[] Status, int PageIndex,
                                                      int PageSize, String token) throws DxException {
        ArrayList<CouponModel> coupons = new ArrayList<CouponModel>();
        Parmars parmars = new Parmars();
        parmars.setCustomerID(CustomerID);
        parmars.setSiteID(SiteID);
        parmars.setSiteClient(SiteClient);
        parmars.setStatus(Status);
        parmars.setPageIndex(PageIndex);
        parmars.setPageSize(PageSize);
        parmars.setToken(token);
        JSONObject data = requestHttpPostData(Constant.FINDCUSTOMERCOUPONS_URL,
                parmars);
        JSONArray jsonArray = data.optJSONArray("Coupons");
        CouponModel coupon;
        if (jsonArray != null && jsonArray.length() != 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.optJSONObject(i);
                coupon = CouponModel.jsonObject2Coupon(jsonObject2);
                coupons.add(coupon);
            }
        }
        return coupons;
    }

    /**
     * 描述：查询当前可用的Coupon，在CouponMarket展示并提供领用
     *
     * @param CustomerID 顾客标识ID
     * @param SiteID     站点ID
     * @param SiteClient 客户端类型（PC、MobileApp、MobileWed、Pad）
     * @param PageIndex  页码，从0开始
     * @param PageSize   每页显示的条数
     * @return 查询到的Coupon集合
     */
    @Override
    public ArrayList<CouponModel> FindMarketCoupons(long CustomerID,
                                                    int SiteID, int SiteClient, int PageIndex, int PageSize)
            throws DxException {
        ArrayList<CouponModel> coupons = new ArrayList<CouponModel>();
        Parmars parmars = new Parmars();
        parmars.setCustomerID(CustomerID);
        parmars.setSiteID(SiteID);
        parmars.setSiteClient(SiteClient);
        parmars.setPageIndex(PageIndex);
        parmars.setPageSize(PageSize);
        JSONObject data = requestHttpPostData(Constant.FINDMARKETCOUPONS_URL,
                parmars);
        JSONArray jsonArray = data.optJSONArray("Coupons");
        CouponModel coupon;
        if (jsonArray != null && jsonArray.length() != 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.optJSONObject(i);
                coupon = CouponModel.jsonObject2Coupon(jsonObject2);
                coupons.add(coupon);
            }
        }
        return coupons;
    }

    /**
     * 描述：绑定Coupon，即 领取Coupon
     *
     * @param CustomerID 顾客标识ID
     * @param CouponCode
     */
    @Override
    public void BindCoupon(long CustomerID, String CouponCode, String token)
            throws DxException {
        Parmars parmars = new Parmars();
        parmars.setCustomerID(CustomerID);
        parmars.setCouponCode(CouponCode);
        parmars.setToken(token);
        JSONObject jsonObject = requestHttpPostAll(Constant.BINDCOUPON_URL,
                parmars);
        // String status = jsonObject.optString(Constant.JSON_STATUS);
    }

    //
    // @Override
    // public PreviewOrderModel PreviewOrder(int CustomerID, String
    // SalesChannelType,
    // String CurrencyCode, int WHID, List<Lines> Lines,
    // boolean BulkRateEnabled, boolean EstimatesShippingFees,
    // String ShippingMethod, String CountryCode, String CouponCode,
    // boolean IsAnonymousCustomer) throws DxException {
    // Parmars parmars = new Parmars();
    // parmars.setCustomerID(CustomerID);
    // parmars.setSalesChannelType(SalesChannelType);
    // parmars.setCurrencyCode(CurrencyCode);
    // parmars.setWHID(WHID);
    // parmars.setLines(Lines);
    // parmars.setBulkRateEnable(BulkRateEnabled);
    // parmars.setEstimatesShippingFees(EstimatesShippingFees);
    // parmars.setShippingMethod(ShippingMethod);
    // parmars.setCountryCode(CountryCode);
    // parmars.setCouponCode(CouponCode);
    // parmars.setIsAnonymousCustomer(IsAnonymousCustomer);
    // JSONObject jsonObject =
    // postOrPutWebInterface(ServerConstant.RequestMethodNameConstant.METHOD_PREVIEWORDER,
    // parmars);
    // JSONObject data =
    // jsonObject.optJSONObject("Data").optJSONObject("PreviewOrder");
    // PreviewOrderModel previewOrderModel = new PreviewOrderModel();
    // previewOrderModel.setGoodsTotal(data.optDouble("GoodsTotal"));
    // previewOrderModel.setOrderDiscount(data.optDouble("OrderDiscount"));
    // previewOrderModel.setGrandTotal(data.optDouble("GrandTotal"));
    // //TODO数据获取之后的组织与处理
    // return previewOrderModel;
    // }

    @Override
    public PreviewOrderModel PreviewOrder(int CustomerID, String CurrencyCode,
                                          int WHID, List<Lines> Lines, String CouponCode, String currencyCode, String token, List<Integer> NotSelectedSkus)
            throws DxException {
        Parmars parmars = new Parmars();
        parmars.setCustomerID(CustomerID);
        parmars.setCurrencyCode(CurrencyCode);
        parmars.setWHID(WHID);
        parmars.setLines(Lines);
        parmars.setCouponCode(CouponCode);
        parmars.setToken(token);
        parmars.setNotSelectedSkus(NotSelectedSkus);
        JSONObject data = requestHttpPostData(Constant.PREVIEWORDER_URL, parmars,
                currencyCode);

        if (data.optBoolean("IsSuccess")) {
            JSONObject preview = data.optJSONObject("PreviewOrder");

            //获取couponCode字段存起来，点击coupon的时候要用到
            JSONObject couponError = preview.optJSONObject("CouponError");
            StringUtil.saveConfig("couponError", String.valueOf(couponError == null ? false : true));
            return PreviewOrderModel.json2PreviewOrderModel(preview);
        }
        return null;
    }

    @Override
    public String DeleteUserCoupon(long customerId, String couponCode,
                                   String token) throws DxException {
        Parmars parmars = new Parmars();
        parmars.setCustomerID(customerId);
        parmars.setCouponCode(couponCode);
        parmars.setToken(token);
        JSONObject jsonObject = requestHttpPostAll(Constant.DELETE_COUPON_URL, parmars);
        String status = jsonObject.optString(Constant.JSON_STATUS);
        return status;
    }

    @Override

    public CouponActiveModel FindDiscountProducts(String couponCode,
                                                  int pageSize, int pageIndex, int categoryId, String orderbyField, long customerID, boolean isFilter, String catrgoryIds)
            throws DxException {
        Parmars parmars = new Parmars();
        parmars.setCouponCode(couponCode);
        parmars.setPageIndex(pageIndex);
        parmars.setCategoryId(categoryId);
        parmars.setPageSize(pageSize);
        parmars.setOrderbyField(orderbyField);
        parmars.setCustomerID(customerID);
        parmars.setFilter(isFilter);
        parmars.setCategoryIds(catrgoryIds);
        JSONObject data = requestHttpPostData(Constant.FIND_DISCOUNT_PRODUCTS_URL, parmars, null);
        if (null != data) {
            JSONObject couponInfo = data
                    .optJSONObject(ServerConstant.CouponActive.COUPON_DISCOUNT_INFO);
            if (null != couponInfo) {

                try {
                    return CouponActiveModel
                            .jsonToCouponActiveModel(couponInfo);
                } catch (JSONException e) {
                    Logger.i("FindDiscountProducts", e.getMessage());
                    return null;
                }
            }
        }
        // try {
        // return CouponActiveModel.jsonToCouponActiveModel(jsonObject);
        // } catch (JSONException e) {
        //
        // }

        return null;
    }

}
